<template>
      <div id="main" class="app">
      <div class="divHead">
        <img src="../assets/images/user.png" @click="toUserPage"/>
      </div>
      <div class="divTitle">
        <div class="divStatic">
          <div class="divDesc">
            <div class="divName">校园送</div>
            <div class="divSend">
                <span><img src="../assets/images/time.png"/> 距离1.5km</span>
                <span><img src="../assets/images/money.png"/> 配送费3元</span>
                <span><img src="../assets/images/location.png"/> 预计时长12min</span>
            </div>
          </div>
        </div>
        <div class="divDesc">
          <button class="my-button" @click="randomFood">点我开启盲盒</button>
          <!-- 简介: 校园送是定位“学生化的美食外送餐饮”，旨为提供校园外卖便利。 -->
        </div>
      </div>
      <div class="divBody">
        <div class="divType">
          <ul>
            <!--分类名称展示-->
            <li v-for="(item,index) in categoryList" :key="index" @click="categoryClick(index,item.id,item.type)" :class="{active:activeType === index}">{{item.name}}</li>
          </ul>
        </div>
        <div class="divMenu">
          <div>
            <!--分类下菜品详情-->
            <div class="divItem" v-for="(item,index) in dishList" :key="index" @click="dishDetails(item)">
              <el-image :src="imgPathConvert(item.image)" >
                <div slot="error" class="image-slot">
                  <img src="../assets/images/noImg.png"/>
                </div>
              </el-image>
              <div>
                <div class="divName">{{item.name}}</div>
                <div class="divDesc">{{item.description}}</div>
                <!-- <div class="divDesc">{{'月销' + (item.saleNum ? item.saleNum : 0)}}</div> -->
                <div class="divBottom"><span>￥</span><span>{{item.price/100}}</span></div>
                <div class="divNum">
                  <div class="divSubtract" v-if="item.number > 0">
                    <img src="../assets/images/subtract.png" @click.prevent.stop="subtractCart(item)"/>
                  </div>
                  <div class="divDishNum">{{item.number}}</div>
                  <div class="divTypes" v-if="item.flavors && item.flavors.length > 0 && !item.number " @click.prevent.stop="chooseFlavorClick(item)">选择规格</div>
                  <div class="divAdd" v-else>
                    <img src="../assets/images/add.png" @click.prevent.stop="addCart(item)"/>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div class="divLayer">
        <div class="divLayerLeft"></div>
        <div class="divLayerRight"></div>
      </div>
      <!--分类信息展示  侧栏-->
      <div class="divCart" v-if="categoryList.length > 0">
        <!--打开购物车-->
          <div :class="{imgCartActive: cartData && cartData.length > 0, imgCart:!cartData || cartData.length<1}" @click="openCart"></div>
          <div :class="{divGoodsNum:1===1, moreGoods:cartData && cartData.length > 99}" v-if="cartData && cartData.length > 0">{{ goodsNum }}</div>
          <div class="divNum">
              <span style="font-size: smaller">预估配送费3元</span>
              <span>￥</span>
              <span>{{goodsPrice+3}}</span>
          </div>
          <div class="divPrice"></div>
        <!--去结算按钮-->
          <div :class="{btnSubmitActive: cartData && cartData.length > 0, btnSubmit:!cartData || cartData.length<1}" @click="toAddOrderPage">去结算</div>
        </div>

      <!--    flavor菜品口味选项框（弹框）   -->
        <van-dialog v-model="dialogFlavor.show" :show-confirm-button="false" class="dialogFlavor" ref="flavorDialog">
          <div class="dialogTitle">{{dialogFlavor.name}}</div>
          <div class="divContent">
            <div v-for="flavor in dialogFlavor.flavors" :key="flavor.id">
                <div class="divFlavorTitle">{{flavor.name}}</div>
                <span v-for="item in JSON.parse(flavor.value)" 
                :key="item"  
                @click="flavorClick(flavor,item)"
                :class="{spanActive:flavor.dishFlavor === item}"
                >{{item}}</span>
            </div>
          </div>
          <div class="divBottom">
            <div><span class="spanMoney">￥</span>{{dialogFlavor.price/100}}</div>
            <div @click="dialogFlavorAddCart">加入购物车</div>
          </div>
          <div class="divFlavorClose" @click="dialogFlavor.show = false">
            <img src="../assets/images/close.png"/>
          </div>
        </van-dialog>
      <!-- 购物车菜品底部上滑  显示 菜品  -->
      <van-popup v-model="cartDialogShow" position="bottom" :style="{ height: '50%' }" class="dialogCart">
          <div class="divCartTitle">
            <div class="title">购物车</div>
            <div class="clear" @click="clearCart">
              <i class="el-icon-delete"></i> 清空
            </div>
          </div>
          <div class="divCartContent">
            <div v-for="item in cartData" :key="item.id" class="divCartItem">
              <el-image :src="imgPathConvert(item.image)" >
                <div slot="error" class="image-slot">
                  <img src="../assets/images/noImg.png"/>
                </div>
              </el-image>
              <div class="divDesc">
                <div class="name">{{item.name}}</div>
                <div class="price">
                  <span class="spanMoney">￥</span>{{item.amount}}</div>
              </div>
              <div class="divNum">
                <div class="divSubtract">
                  <img src="../assets/images/subtract.png" @click="cartNumberSubtract(item)"/>
                </div>
                <div class="divDishNum">{{item.number}}</div>
                <div class="divAdd">
                  <img  src="../assets/images/add.png" @click="cartNumAdd(item)"/>
                </div>
              </div>
              <div class="divSplit"></div>
              </div>
          </div>
        </van-popup>
      <!--菜品详情弹框-->
      <van-dialog v-model="detailsDialog.show"
                  :show-confirm-button="true"
                  class="detailsDialog"
                  ref="detailsDialog"
                  v-if="detailsDialog.show"
                  >
        <div class="divContainer">
          <el-image :src="imgPathConvert(detailsDialog.item.image)" >
            <div slot="error" class="image-slot">
              <img src="../assets/images/noImg.png"/>
            </div>
          </el-image>
          <div class="title">{{detailsDialog.item.name}}</div>
          <div class="content">{{detailsDialog.item.description}}</div>
        </div>
        <div class="divNum">
          <div class="left">
            <span>￥</span><span>{{detailsDialog.item.price/100}}</span>
          </div>
          <div class="right">
              <div class="divSubtract" v-if="detailsDialog.item.number > 0">
                <img src="../assets/images/subtract.png" @click="subtractCart(detailsDialog.item)"/>
              </div>
              <div class="divDishNum">{{detailsDialog.item.number}}</div>
              <div class="divTypes" v-if="detailsDialog.item.flavors && detailsDialog.item.flavors.length > 0 && !detailsDialog.item.number " @click ="chooseFlavorClick(detailsDialog.item)">选择规格</div>
              <div class="divAdd" v-else>
                <img src="../assets/images/add.png" @click="addCart(detailsDialog.item)"/>
              </div>
          </div>
        </div>
        <div class="detailsDialogClose" @click="detailsDialog.show = false">
          <img src="../assets/images/close.png"/>
        </div>
      </van-dialog>
        <!--套餐详情弹框-->
        <van-dialog v-model="setMealDialog.show" 
                    :show-confirm-button="false" 
                    class="setMealDetailsDialog" 
                    ref="setMealDetailsDialogd"
                    v-if="setMealDialog.show"
                    >
          <div class="divContainer">
            <div class="title">{{setMealDialog.item.name}}</div>
              <div class="item" v-for="(item,index) in setMealDialog.item.list" :key="index">
                <el-image :src="imgPathConvert(item.image)">
                  <div slot="error" class="image-slot">
                    <img src="../assets/images/noImg.png"/>
                  </div>
                </el-image>
                <div class="divSubTitle">{{item.name + '(' + item.copies + '份)' }}
                  <div class="divPrice">
                    <span>￥</span><span>{{item.price/100}}</span>
                  </div>
                </div>                
                <div class="content">{{item.description}}</div>
              </div>
            </div>
          <div class="divNum">
              <div class="left">
                <span>￥</span><span>{{setMealDialog.item.price/100}}</span>
              </div>
              <div class="right">
                  <div class="divSubtract" v-if="setMealDialog.item.number > 0">
                    <img src="../assets/images/subtract.png" @click="subtractCart(setMealDialog.item)"/>
                  </div>
                  <div class="divDishNum">{{setMealDialog.item.number}}</div>
                  <div class="divAdd" v-if="setMealDialog.item.number">
                    <img src="../assets/images/add.png" @click="addCart(setMealDialog.item)"/>
                  </div>
                  <div class="addCart"  @click="addCart(setMealDialog.item)" v-if="!setMealDialog.item.number">加入购物车</div>
              </div>
          </div>
          <div class="detailsDialogClose" @click="setMealDialog.show = false">
            <img src="../assets/images/close.png"/>
          </div>
        </van-dialog>
    </div>
</template>

<script>
import {
  randomFoodApi, categoryListApi,dishListApi,setmealListApi,setMealDishDetailsApi,clearCartApi,updateCartApi,addCartApi,cartListApi,saleGiveApi
} from '../assets/api/main'
import{imgPath} from '../assets/js/common'
import _ from 'lodash';
import {base} from '../assets/js/base'
import router from '@/router'
export default {
    name:'main',
    data(){
      return {
        //左边菜品类别index
        activeType:0,
        categoryList:[],//菜品分类数据
        categoryId:undefined,
        dishList:[],//菜品数据
        cartData:[],//购物车数据
        dialogFlavor:{
          name:'',
          flavors:[],
          dishId:undefined,
          price:undefined,
          show:false,
          image:''
        },
        cartDialogShow:false,
        detailsDialog:{ // 菜品详情弹框数据
          show:false,
          item:{image:''}
        },
        setMealDialog:{ // 套餐详情弹框
          show:false,
          item:{}
        },
      }
    },
    computed:{
      goodsNum(){
        let num = 0;
        this.cartData.forEach(item=>{
          num += item.number 
        });
        if(num <99){
          return num
        }else{
          return '99+'
        }
      },
      goodsPrice(){
        let price = 0;
        this.cartData.forEach(item=>{
          price += (item.number * (item.amount*100))
          
        });
        return price/100
      }
    },
    created(){
      base(document,window)
    },
    watch:{
      'dialogFlavor.show'(flag){
        if(flag){
          document.querySelector('.divCart').style.zIndex = 1;
        }else{
          document.querySelector('.divCart').style.zIndex = 3000;
        }
      },
    },
    mounted(){
      this.initData()
    },
    methods:{
      //初始化数据
      initData(){
        Promise.all([categoryListApi(),cartListApi({})]).then(res=>{
          //获取分类数据
          console.log(res);
          if(res[0].data.code === 1){
            this.categoryList = res[0].data.data;
            if(Array.isArray(res[0].data.data) && res[0].data.data.length > 0){
              this.categoryId = res[0].data.data[0].id;
              if(res[0].data.data[0].type === 1){
                this.getDishList()
              }else{
                this.getSetmealData()
              }
            }
          }else{
            this.$notify({ type:'warning', message:res[0].data.smsg});
          }
          //获取菜品数据
          if(res[1].data.code === 1){
          this.cartData = res[1].data.data
          }else{
            this.$notify({ type:'warning', message:res[1].data.msg});
          }
        })
      },
      async randomFood(){
      
         const res = await randomFoodApi({});
         if(res.data.code === 1){
           this.cartData = res.data.data
           this.$message.success("盲盒菜品已加入购物车");
           this.getCartData()
         }else{
           this.$notify({ type:'warning', message:res.data.msg});
         }
       },
       
      //分类点击
      categoryClick(index,id,type){
        this.activeType = index;
        this.categoryId = id;
        if(type === 1){//菜品
          this.getDishList()
        }else{
          this.getSetmealData()
        }
      },
      //获取菜品数据
      async getDishList(){
        if(!this.categoryId){
          return
        }
        const res = await dishListApi({categoryId:this.categoryId,status:1});
        if(res.data.code === 1){
          let dishList = res.data.data;
          const cartData  = this.cartData;
          if(dishList.length > 0 && cartData.length > 0){
            dishList.forEach(dish=>{
              cartData.forEach(cart=>{
                if(dish.id === cart.dishId){
                  dish.number = cart.number
                }
              })
            })
          }
          this.dishList = dishList
        }else{
          this.$notify({ type:'warning', message:res.data.msg});
        }
      },
      //获取套餐数据setmealId
      async getSetmealData(){
        if(!this.categoryId){
          return
        }
        const res = await setmealListApi({categoryId:this.categoryId,status:1});
        if(res.data.code === 1){
            let dishList = res.data.data;
            const cartData  = this.cartData;
            if(dishList.length > 0 && cartData.length > 0){
              dishList.forEach(dish=>{
                cartData.forEach(cart=>{
                  if(dish.id === cart.setmealId){
                    dish.number = cart.number
                  }
                })
              })
            }
            this.dishList = dishList
        }else{
          this.$notify({ type:'warning', message:res.data.msg});
        }
      },
      async getSaleGive(){
        const res = await saleGiveApi();
        if(res.data.code === 1&& res.data.data!=null){
            this.$message.success("恭喜获得买赠商品,快去购物车看看")
          
        }
      },
      //获取购物车数据
      async getCartData(){
        
       await this.getSaleGive()
        const res = await cartListApi({});
        if(res.data.code === 1){
          this.cartData = res.data.data
        }else{
          this.$notify({ type:'warning', message:res.data.msg});
        }
      },
      
      //菜单中往购物车中添加商品
      async addCart(item){
        let params = {
          amount:item.price/100,//金额
          dishFlavor:item.dishFlavor,//口味  如果没有传undefined
          dishId:undefined,//菜品id
          setmealId:undefined,//套餐id
          name:item.name,
          image:item.image
        };
        if(Array.isArray(item.flavors)){//表示是菜品
          params.dishId = item.id
        }else{//表示套餐 套餐没有口味
          params.setmealId = item.id
        }
        const res = await addCartApi(params);
        if(res.data.code === 1){
          this.dishList.forEach(dish=>{
            if(dish.id === item.id){
              dish.number = res.data.data.number
            }
          });
          if(this.setMealDialog.show){
            item.number = res.data.data.number
          }
          this.getCartData()
        }else{
          this.$notify({ type:'warning', message:res.data.msg});
        }
      },

      //菜单中减少选中的商品
      async subtractCart(item){
          let params = {
            dishId:item.id,
          };
          if(!Array.isArray(item.flavors)){
            params = {
              setmealId:item.id,
            }
          }
          const res = await updateCartApi(params);
          if(res.data.code === 1){
          this.dishList.forEach(dish=>{
            if(dish.id === item.id){
              dish.number = (res.data.data.number === 0 ? undefined : res.data.data.number)
            }
          });
          if(this.setMealDialog.show){
            item.number = (res.data.data.number === 0 ? undefined : res.data.data.number)
          }
          // this.getCartData()
          }else{
            this.$notify({ type:'warning', message:res.data.msg});
          }
      },
      
      //展开购物车
      openCart(){
        if(this.cartData.length > 0){
          this.cartDialogShow = true
        }
      },
      //购物车中增加商品数量
      async cartNumAdd(item){
        let params = {
          amount:item.amount,//金额
          dishFlavor:item.dishFlavor,//口味  如果没有传undefined
          dishId:item.dishId,//菜品id
          setmealId:item.setmealId,//套餐id
          name:item.name,
          image:item.image
        };
      
        const res = await addCartApi(params);
        if(res.data.code === 1){
          this.dishList.forEach(dish=>{
            if(dish.id === (item.dishId || item.setmealId)){
              dish.number = res.data.data.number
            }
          });
          this.getCartData()
        }else{
          this.$notify({ type:'warning', message:res.data.msg});
        }
      },
      //购物车中减少商品数量
      async cartNumberSubtract(item){
        let params = {
            dishId:item.dishId,
            setmealId:item.setmealId,
          };
          const res = await updateCartApi(params);
          if(res.data.code === 1){
          this.dishList.forEach(dish=>{
            if(dish.id === (item.dishId || item.setmealId)){
              dish.number = (res.data.number === 0 ? undefined : res.data.number)
            }
          });
          this.getCartData()
          }else{
            this.$notify({ type:'warning', message:res.data.msg});
          }
      },
      
      //修改商品列表中的数据number
      changeDishList(item){
        for(let ele of this.dishList){
          if(ele.id === (item.setmealId || item.dishId)){
            ele.number = item.number
          }
        }
      },
      
      //清空购物车
      async clearCart(){
          const res = await clearCartApi();
          if(res.data.code === 1){
            for(let ele of this.dishList){
              ele.number = undefined
            }
            this.cartData = [];
            this.cartDialogShow = false
          }else{
            this.$notify({ type:'warning', message:res.data.msg});
          }
      },
      //点击选择规格
      chooseFlavorClick(item){
        this.dialogFlavor = {
          name:'',
          flavors:[],
          dishId:undefined,
          price:undefined,
          show:false
        };
        this.dialogFlavor={
          name:item.name,
          flavors:item.flavors,
          dishId:item.id,
          price:item.price,
          show:true,
          image:item.image
        }
      },
      flavorClick(flavor,item){
        flavor.dishFlavor = item;
        //强制刷新dialog的dom
        this.dialogFlavor.show = false;
        this.dialogFlavor.show = true;
      },
      //选择规格加入购物车
      dialogFlavorAddCart(){
        const dialogFlavor = this.dialogFlavor;
        let flag = true;
        let dishFlavor = [];
        dialogFlavor.flavors.forEach(item=>{
          if(item.dishFlavor){
            dishFlavor.push(item.dishFlavor)
          }else{
                flag = false;
                Notify({ type: 'warning', message: '请选择'+ item.name });
          }
        });
        if(flag){
          this.addCart({
            price:dialogFlavor.price,
            dishFlavor:dishFlavor.join(","),
            id:dialogFlavor.dishId,
            flavors:[],
            image:dialogFlavor.image,
            name:dialogFlavor.name
          });
          this.dialogFlavor.show = false;
        }
        
      },
      //网络图片路径转换
      imgPathConvert(path){
        return imgPath(path);
      },
      //跳转到去结算界面
      toAddOrderPage(){
        if(this.cartData.length > 0){
          window.requestAnimationFrame(()=>{
           router.push('/addOrder')
          })
        }
      },
      toUserPage(){
        window.requestAnimationFrame(()=>{
         router.push('/user')
        })
      },
      async dishDetails(item){
        //先清除对象数据，如果不行的话dialog使用v-if
        this.detailsDialog.item = {};
        this.setMealDialog.item = {};
        if(Array.isArray(item.flavors)){
          this.detailsDialog.item = item;
          this.detailsDialog.show = true
        }else{
          //显示套餐的数据
          const res = await setMealDishDetailsApi(item.id);
          if(res.data.code === 1){
            this.setMealDialog.item = {...item,list:res.data.data};
            this.setMealDialog.show = true;
          }else{
            this.$notify({ type:'warning', message:res.data.msg});
          }
        }

      }

    }
 
}
</script>

<style>
.my-button {
  width: 100%;
  height: 45px;
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 10px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  transition-duration: 0.4s;
  border-radius: 6px;
}

.my-button:hover {
  background-color: #3e8e41;
}

.my-button:active {
  background-color: #3e8e41;
  transform: translateY(2px);
}

@import url(../assets/styles/index.css);
@import url(../assets/styles/main.css);
@import url(../assets/styles/vant.min.css);
</style>